//
//  JLSButtomTabBar.m
//  看点
//
//  Created by 焦林生 on 15/12/15.
//  Copyright © 2015年 jiaolinsheng. All rights reserved.
//

#import "JLSButtomTabBar.h"
#import "JLSButtomTabBarBtn.h"

@interface JLSButtomTabBar ()
//记录当前被选中tabBarBtn
@property (nonatomic, weak) UIButton *selectedBtn;

@end
@implementation JLSButtomTabBar

//传入两张图片
- (void)addButtomTabBarBtnWithImage:(NSString *)norImage selected:(NSString *)selected title:(NSString *)title
{

     //1 创建一个按钮
    JLSButtomTabBarBtn *btn = [[JLSButtomTabBarBtn alloc] init];
    
    //2 设置按钮的背景图片
    [btn setImage:[UIImage imageNamed:norImage] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:selected] forState:UIControlStateSelected];
    
    //设置文字
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    
    //3 把按钮添加到底部的 buttomTabBar中
    [self addSubview:btn];
    
    //4 为按钮绑定一个点击事件
    [btn addTarget:self action:@selector(didClickTabBarBtn:) forControlEvents:UIControlEventTouchDown];
    
}

//tabBar 点击事件
- (void)didClickTabBarBtn:(UIButton *)button
{

    //1 让当前被选中的按钮取消选中状态
    self.selectedBtn.selected  = NO;
    
    //2 设置传进来的按钮为选中状态
    button.selected = YES;
    
    //3 记录传进来的按钮为当前按钮
    self.selectedBtn = button;
    
    //4 获取选中按钮的索引 调用代理的协议方法,让tabBarController来切换当前显示的子控制器
    int index = (int)button.tag;
    
    //判断代理是否实现了协议中的方法 实现了就调用
    if ([self.delegate respondsToSelector:@selector(buttomTabBar:didClickButtomTabBarWithIndex:)]) {
        
        [self.delegate buttomTabBar:self didClickButtomTabBarWithIndex:index];
    }
}

#pragma mark - 布局子控件
- (void)layoutSubviews
{

    [super layoutSubviews];
    
    //获取子控件的数量
    NSUInteger count = self.subviews.count;
    
    //设置 frame
    CGFloat w = self.width / count;
    CGFloat h = self.height;
    CGFloat y = 0;
    for (int i = 0; i < count; i++) {
        CGFloat x = i * w;
        
        //获取对应的按钮.设置 frame
        UIButton *button = self.subviews[i];
        button.frame = CGRectMake(x, y, w, h);
        
        //为每一个按钮绑定一个 tag
        button.tag = i;
        
        //如果按钮为0 就设置第0个按钮为当前选中状态
        if (i == 0) {
            button.selected = YES;
            self.selectedBtn = button;
        }
    }
}


@end
